package cn.jbolt.ndemo;

import cn.hutool.json.JSONUtil;
import cn.jbolt.ai.core.chain.ChainContext;
import cn.jbolt.ai.core.chain.node.provider.CommonNodeProvider;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.stereotype.Component;

@Component
public class DataProcessNode implements CommonNodeProvider {
    @Override
    public void provide(JsonNode nodeConfig, ChainContext context) {

        String result = context.getAttr("ai_result");
        boolean isJson = JSONUtil.isTypeJSON(result);
        try {

            if (!isJson) {
                result = result.substring(result.indexOf("{"), result.lastIndexOf("}") + 1);
            }
            JSONObject data = JSON.parseObject(result);
            JSONArray list = data.getJSONArray("list");
            if (list != null && list.isEmpty() == false) {
                for (int i = 0; i < list.size(); i++) {
                    JSONObject item = list.getJSONObject(i);
                    Double value = item.getDouble("result");
                    //item.pass = item.result >= item.min && item.result <= item.max;
                    String min = item.getString("min");
                    Double minValue = 0.0;
                    //正则表达式从min里提取数字
                    if (min != null) {
                        min = min.replaceAll("[^0-9]", "");
                        minValue = Double.parseDouble(min);
                    }

                    //Double min = (Double) string;
                    String max = item.getString("max");
                    Double maxValue = Integer.MAX_VALUE * 1.0;
                    //正则表达式从min里提取数字
                    if (max != null) {
                        max = max.replaceAll("[^0-9]", "");
                        maxValue = Double.parseDouble(min);
                    }

                    item.put("pass", value == null ? false : (value >= minValue && value <= maxValue));
                }
            }

            context.sendResponseMsg(data.toJSONString(), "json");
        } catch (Exception e) {
            e.printStackTrace();
            context.sendErrorMsg("程序异常，请重试...");
        }
    }
}
